import axios from "axios";
import { message } from "@/hooks/message";
// 处理请求取消逻辑
const CancelToken = axios.CancelToken;
const apiCancel = {};
const symbolCancel = new Map();
let cancel;

//
axios.defaults.timeout = 520000;
// 返回其他状态吗
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 888; // 默认的
};
// 跨域请求，允许保存cookie
axios.defaults.withCredentials = true;
// 未封装的请求方法
export default axios;

// 可取消请求方法
export function cancelRequest(params, request) {
  const { cancelSymbolKey, ...requestParam } = params || {};
  if (!apiCancel[cancelSymbolKey]) {
    apiCancel[cancelSymbolKey] = Symbol();
  }
  if (symbolCancel.has(apiCancel[cancelSymbolKey])) {
    cancel = symbolCancel.get(apiCancel[cancelSymbolKey]);
  }
  typeof cancel === "function" && cancel();
  return (request || axios)({
    ...requestParam,
    cancelToken:
      requestParam.cancelToken ||
      new CancelToken(function executor(c) {
        // executor 函数接收一个 cancel 函数作为参数
        symbolCancel.set(apiCancel[cancelSymbolKey], c);
      }),
  });
}
